<template>
  <div class="permission-container">
    <div class="app-container">
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="showDialog({ type: 1, pid: '0' })">添加权限</el-button>
        </div>
        <!-- 表格 -->
        <el-table :data="permissionList" border row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="showDialog({ type: 2, pid: row.id })">添加</el-button>
              <el-button type="text" @click="showEditDialog(row.id)">编辑</el-button>
              <el-button type="text" @click="deletePermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <permission-dialog 
      ref="permissionRef"
      :visible="permissionVisible"
      :type="type"
      :pid="pid"
      @dialog-close="dialogClose"
      @fetch-permission-list="fetchPermissionList"
    />
  </div>
</template>

<script>
import { getPermissionList, delPermission } from '@/api/permission'
import transTree from '@/utils/transTree'
import PermissionDialog from './components/permission-dialog'
export default {
  components: {
    PermissionDialog
  },
  data() {
    return {
      // 权限列表数据
      permissionList: [],
      // 控制弹窗显示与隐藏
      permissionVisible: false,
      type: '',
      pid: ''
    }
  },
  created() {
    this.fetchPermissionList()
  },
  methods: {
    // 获取权限点列表数据
    async fetchPermissionList() {
      const res = await getPermissionList()
      this.permissionList = transTree(res.data, '0')
    },
    // 显示弹窗
    showDialog({ type, pid }) {
      this.type = type
      this.pid = pid
      this.permissionVisible = true
    },
    // 关闭弹窗
    dialogClose() {
      this.permissionVisible = false
    },
    // 点击编辑时，打开弹窗
    showEditDialog(id) {
      this.permissionVisible = true
      this.$refs.permissionRef.fetchPermissionDetail(id)
    },
    // 删除权限点
    deletePermission(id) {
      this.$confirm('此操作将永久删除该权限点, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发起请求
        const res = await delPermission(id)
        // 提示用户
        this.$message.success(res.message)
        // 刷新列表
        this.fetchPermissionList()
      }).catch(() => {
      });
    }
  }
}
</script>

<style>

</style>